import {Component, OnInit} from '@angular/core';
import {UserInfo} from "../../modals/basic.modal";
import {ActivatedRoute, Router} from "@angular/router";
import {AlertComponent} from "../../unit/alert";
import {BasicService} from "../../unit/basic-service";
import {environment} from "../../../environments/environment";

@Component({
    selector: 'app-login',
    templateUrl: './login.page.html',
    styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
    formData: UserInfo;
    loginLoading: boolean;

    constructor(private route: Router,
                public alertComponent: AlertComponent,
                private activateInfo: ActivatedRoute,
                private basicService: BasicService,
    ) {
    }

    ngOnInit() {
        this.formData = {
            username: '513725199005259342',
            password: '123456',
        };
    }

    loginIn() {
        const userData = {
            username: this.formData.username,
            password: this.formData.password,
            loginType: 'inside_login'
        };
        if (userData.username && userData.password) {
            this.loginLoading = true;
            this.basicService.postData('login', userData).then(res => {
                if (res.code === 0) {
                    localStorage.setItem('cardNumber', res.idCard); // save card number
                    localStorage.setItem('medicalToken', res.token);
                    this.goToPage('tabs');
                } else {
                    this.alertComponent.presentAlert(res.text).then();
                }
                this.loginLoading = false;
            }).catch(error => {
                const stringError = JSON.stringify(error);
                this.alertComponent.presentAlert(stringError).then();
                this.loginLoading = false;
            })
        } else {
            this.alertComponent.presentAlert('请填写身份证和密码').then();
        }
    }

    goToPage(url, type = 0) {
        this.route.navigate([`/${url}`], {queryParams: {type}}).then();
    }

}
